from myImage.CImage import CImage
import math
import os
import pandas as pd
import numpy as np
class CPatch:
    M = {'seed': 0, 'seed_1': 1, 'partial': 2}

    @staticmethod
    def getClassId(label):
        return CPatch.M.get(label)

    # 定义类的构造方法
    def __init__(self, fileDetectRes, iou, isLoadFile=True, data=[]):

        if isLoadFile == True: ## 读入保存好的 子图片的 boundingbox
            detects= self.readDetectFile(fileDetectRes)
        else:
            detects = self.transformDetects(data)

        nums = len(detects)
        if nums > 0:
            ins = detects[:, 1] >= iou
            detects = detects[ins]

        self.detects = detects

    ## 转换格式
    def transformDetects(self, data):
        nums = len(data)

        if nums > 0:
            detects = np.pad(data, ((0,0), (0,2)), 'constant', constant_values=0)
        else:
            detects = np.empty((nums, 8))

        return detects
    ##读取文件
    def readDetectFile(self, fileDetectRes):
        if os.path.getsize(fileDetectRes) == 0:
            return np.empty((0, 8))

        df = pd.read_csv(fileDetectRes, sep=' ', header=None)

        nums = len(df)
        detects = np.zeros((nums, 8))
        if nums > 0:
            df.replace({0: CPatch.M}, inplace=True)

            detects[:, 0:6] = df.values
        return detects

    def findEdgeBox(self):##寻找边缘元素
        if len(self.detects) == 0:
            return

        wSize = CImage.wsize - 1

        ins2 = self.detects[:, 2] <=0
        ins3 = self.detects[:, 3] <=0
        ins4 = self.detects[:, 4] >=wSize
        ins5 = self.detects[:, 5] >=wSize

        # self.detects[:, 6] = ins2 or ins3 or ins4 or ins5
        self.detects[:, 6] = ins2 | ins3 | ins4 | ins5

    def supressEdges(self, ratio):##抑制边缘元素
        if len(self.detects) == 0:
            return

        self.detects[:, 7] = self.detects[:, 1]##保存原来的prob

        ins = self.detects[:, 6] == 1
        self.detects[ins, 1] = self.detects[ins, 1] * ratio##边缘元素的概率下调